package pl.un4giv3n.mightvsmagic.action;

import javax.persistence.EntityManager;

import pl.un4giv3n.mightvsmagic.entity.UserAttribute;
import pl.un4giv3n.mightvsmagic.utils.UserUtil;

/**
 * @author andrzejewskia
 *	change user attributes
 */
public class DevelopAction extends DevelopPageAction {

	private static final long serialVersionUID = 1L;
	/**
	 *  attibute to develop
	 */
	private UserAttribute attribute;

	/* (non-Javadoc)
	 * @see pl.un4giv3n.mightvsmagic.action.DevelopPageAction#execute()
	 */
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		entityManager.getTransaction().begin();
		long gold = user.getGold();
		long selectedSkillCost = UserUtil.getNextSkillCost(user, attribute);
		if (gold < selectedSkillCost) {
			addActionError("Nie stać się na trening tej umiejętności!");
			entityManager.getTransaction().rollback();
			return INPUT;
		}
		updateAttribute();
		user.removeGold(selectedSkillCost);
		entityManager.merge(user);
		entityManager.flush();
		entityManager.getTransaction().commit();
		entityManager.close();
		return SUCCESS;
	}

	private void updateAttribute() {
		if (attribute == UserAttribute.STAMINA) {
			user.setStamina(user.getStamina()+1);
		}else if(attribute == UserAttribute.STRENGHT){
			user.setStrenght(user.getStrenght()+1);
		}else if(attribute == UserAttribute.MANA){
			user.setMana(user.getMana()+1);
		}else if(attribute == UserAttribute.ATTACK){
			user.setAttack(user.getAttack() +1);
		}else if(attribute == UserAttribute.PARRY){
			user.setParry(user.getParry()+1);
		}else if(attribute == UserAttribute.LIFE){
			user.setLife(user.getLife() + 1);
			user.setHp(user.getLife()*10);
		}
	}

	public void setAttribute(String attribute) {
		this.attribute = UserAttribute.valueOf(attribute);
	}

	public UserAttribute getAttribute() {
		return attribute;
	}

}
